package top.magicpotato.sample.component;

import javafx.beans.DefaultProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.stage.StageStyle;
import javafx.util.Duration;
import org.pomo.toasterfx.model.ToastParameter;
import top.magicpotato.sample.pojo.record.ConnectionInfo;
import top.magicpotato.sample.store.DbStore;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;


// 设置默认属性 方便在fxml中赋值
@DefaultProperty("content")
public class ConnectionDbDialog extends Dialog<ConnectionInfo> {

    @FXML
    private TextField tfNickName;

    @FXML
    private TextField tfDbName;

    @FXML
    private TextField tfHost;

    @FXML
    private TextField tfUser;

    @FXML
    private PasswordField tfPassword;

    @FXML
    private ChoiceBox<Boolean> useInformationSchema;

    @FXML
    private ChoiceBox<Boolean> remarks;

    @FXML
    private ChoiceBox<Boolean> useUnicode;

    @FXML
    private TextField characterEncoding;

    @FXML
    private ChoiceBox<Boolean> useSSL;

    @FXML
    private TextField serverTimezone;

    @FXML
    private ChoiceBox<Boolean> allowPublicKeyRetrieval;

    private ConnectionDbDialog() throws IOException {
        URL location = getClass().getResource("/top/magicpotato/sample/connection_db_dialog.fxml");
        ResourceBundle resources = ResourceBundle.getBundle("top.magicpotato.sample.main");
        FXMLLoader fxmlLoader = new FXMLLoader(location, resources);
        // 将自身实例设置为根节点
        fxmlLoader.setRoot(this);
        // controller也设置为自身
        fxmlLoader.setController(this);
        // 该方法必须设置完上面俩参数后才可以调用
        fxmlLoader.load();

        // 获取布局根容器
        DialogPane dp = getDialogPane();

        // 设置转换器，转换器是一个重要概念 他表示点击确定按钮后返回的数据结构
        setResultConverter(this::formResult);

        // 不在任务栏展示图标
        initStyle(StageStyle.UTILITY);

        // 添加确定和取消按钮
        dp.getButtonTypes().addAll(ButtonType.CANCEL, ButtonType.OK);

        Button btnOk = (Button) dp.lookupButton(ButtonType.OK);
        btnOk.addEventFilter(ActionEvent.ACTION, event -> {
            if (DbStore.get(tfNickName.getText()) != null) {
                ToastBar.getInstant().fail("提示", "昵称已存在", ToastParameter.builder().timeout(Duration.seconds(2)).build());
                // 此操作会阻止事件继续传报
                event.consume();
            }
        });
    }

    /**
     * 设置对应的get set方法后才可以在fxml中赋值，而且get set必须成对出现
     *
     * @return
     */
    public Node getContent() {
        return getDialogPane().getContent();
    }

    public void setContent(Node node) {
        getDialogPane().setContent(node);
    }

    /**
     * 转换器 点击按钮后返回的数据构造
     *
     * @param bt
     * @return
     */
    private ConnectionInfo formResult(ButtonType bt) {
        // 如果点击的是确定按钮则 封装数据对象返回
        if (bt.getButtonData() == ButtonBar.ButtonData.OK_DONE) {
            return new ConnectionInfo(
                    tfNickName.getText(),
                    tfDbName.getText(),
                    tfHost.getText(),
                    tfUser.getText(),
                    tfPassword.getText(),
                    useInformationSchema.getValue(),
                    remarks.getValue(),
                    useUnicode.getValue(),
                    characterEncoding.getText(),
                    useSSL.getValue(),
                    serverTimezone.getText(),
                    allowPublicKeyRetrieval.getValue()
            );
        }
        return null;
    }

    public static ConnectionDbDialog getInstance() {
        return getInstance(null);
    }

    public static ConnectionDbDialog getInstance(ConnectionInfo connectionInfo) {
        try {
            ConnectionDbDialog connectionDbDialog = new ConnectionDbDialog();
            if (connectionInfo != null) {
                connectionDbDialog.tfNickName.setText(connectionInfo.nickName());
                connectionDbDialog.tfDbName.setText(connectionInfo.dbName());
                connectionDbDialog.tfHost.setText(connectionInfo.host());
                connectionDbDialog.tfUser.setText(connectionInfo.username());
                connectionDbDialog.tfPassword.setText(connectionInfo.password());
                connectionDbDialog.useInformationSchema.setValue(connectionInfo.useInformationSchema());
                connectionDbDialog.remarks.setValue(connectionInfo.remarks());
                connectionDbDialog.useUnicode.setValue(connectionInfo.useUnicode());
                connectionDbDialog.characterEncoding.setText(connectionInfo.characterEncoding());
                connectionDbDialog.useSSL.setValue(connectionInfo.useSSL());
                connectionDbDialog.serverTimezone.setText(connectionInfo.serverTimezone());
                connectionDbDialog.allowPublicKeyRetrieval.setValue(connectionInfo.allowPublicKeyRetrieval());
            }
            return connectionDbDialog;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
